﻿/**
 * FansUnion-JS-AJAX1.0
 *
 * QQ: 240370818
 * Email: LeiWen@FansUnion.cn
 * Date:2013.12.12
 * Copyright 2013-2014, leiwen,zhanshaolong
 */
/**
 *Ajax工具类
 */ 
 var AjaxUtil = (function(win, dom) {
 
 /**
  *接受的类型
  */
	var acceptTypes = {
		xml: "application/xml, text/xml, */*",
		html: "text/html, */*",
		script: "text/javascript, application/javascript, */*",
		json: "application/json, text/javascript, */*",
		text: "text/plain, */*"
	};
	
	/**
     *构造请求对象
     */
	var getHttpReq = function(mineType) {
		var httpReq;
		try {
			httpReq = new XMLHttpRequest();
		} catch (e) {
			try {
				httpReq = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					httpReq = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
				}
			}
		}
		if (httpReq.overrideMimeType){
			httpReq.overrideMimeType(mineType || 'text/plain');
		}
		return httpReq;
	};
	
	/**
    *获得数据
    */
	var getData = function(xmlHttp, dataType){
		switch(dataType){
			case 'json' :
				return new Function('return ' + xmlHttp.responseText)();
			case 'script' :
				return eval('0, (' + xmlHttp.responseText + ')');
			case 'xml' :
				return xmlHttp.responseXML;
			case 'text' :
			case 'html' :
				return xmlHttp.responseText;
		}
	};
	
	var AjaxUtil = win.AjaxUtil || {};
	
	/**
  *AJAX方法
  *options:请求参数
  */
	AjaxUtil.ajax = function(options) {
		var success = options.success;
		var failed = options.failed;
		var param = options.param;
		var complete = options.complete;
		var dataType = options.dataType || 'text';
		var type = options.type || 'POST';
		var url = options.url;
		var sync = options.sync;
		var httpReq = getHttpReq();
		var args = '';
		var len = 0;
		if(param){
			for(var p in param){
				args += '&' + p + '=' + encodeURIComponent(param[p]);
			}
			args = args.substring(1);
		}
		if(/^get$/i.test(type) && (len = args.length)){
			url = url + '?' + args;
			args = null;
		}
		httpReq.open(type, url, !sync);
		httpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
		httpReq.setRequestHeader('Content-Length', len);
		httpReq.setRequestHeader('Connection', 'close');
		httpReq.setRequestHeader('Accept', acceptTypes[dataType]);
		//请求完毕
		httpReq.onreadystatechange = function(){
			if(httpReq.readyState==4){
				var status = httpReq.status;
				var data = getData(httpReq, dataType);
				if(status == 200) {
					success && success(data);
		        }else if(status >= 400 && status < 600){
		        	failed && failed(httpReq.statusText);
		        }
				complete && complete(data);
			}
		};
		httpReq.send(args);
	};
	return AjaxUtil;
})(window, document);